package com.trippin.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.trippin.DB.DBHandler;
import com.trippin.DB.entities.UserEntity;
import com.trippin.Utils.ServletUtil;
import com.trippin.Utils.ServletUtilConstants;

@SuppressWarnings("serial")
public class UserServlet extends HttpServlet {
	
	private static final Logger logger = Logger.getLogger(UserServlet.class.getCanonicalName());
	
	private static DBHandler dbHandlerInstance = DBHandler.INSTANCE;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		Action action = ServletUtil.getActionFromHeader(req,resp,LocationServlet.class.toString());		
		long userId = ServletUtil.getLongFromHeader(req, resp, ServletUtilConstants.USER_ID,
				TripServlet.class.toString(), action.getName());

		try {
		String bodyResponse = "";				
		switch(action) {
		case GET_USER_PROFILE:
			bodyResponse = getUser(userId);
			break;
			
		case CREATE_USER_PROFILE:
		case UPDATE_USER_PROFILE:
			bodyResponse = createOrUpdateUser(userId, req, resp, action);
			break;

		default:
			ServletUtil.printError(resp,action.getName(), AttractionServlet.class.getName(), ServletUtilConstants.ERROR_WRONG_ACTION_NAME);
			break;
		}

		ServletUtil.createResponse(resp, action.getName(), bodyResponse);
		
		} catch(Exception e) {
			ServletUtil.printError(resp,action.getName(), UserServlet.class.getName(), e.getMessage());
			logger.log(Level.SEVERE,e.toString(), e);
		}
		
	}

	private String getUser(long userId) {
		UserEntity user = dbHandlerInstance.getUserById(userId);
		return ServletUtil.getResponseBody(user);
	}
	
	private String createOrUpdateUser(long userId, HttpServletRequest req, 
			HttpServletResponse resp, Action action) throws IOException {
		BufferedReader in = req.getReader();
		String reqBodyString = ServletUtil.getRequestBody(in);
		in.close();

		UserEntity user = (UserEntity)ServletUtil.getFromJSON(reqBodyString, UserEntity.class);
		switch(action) {
		case CREATE_USER_PROFILE:
			String[] requireds = {ServletUtilConstants.REQUIRED_NAME};
			ServletUtil.checkRequiredFields(reqBodyString,requireds, resp, action.getName(), LocationServlet.class.getName());
			user = dbHandlerInstance.createUser(userId, user);
			break;
		case UPDATE_USER_PROFILE:
			user = dbHandlerInstance.updateUser(userId, user);
			break;
		}			
		return ServletUtil.getResponseBody(user);
	}

}
